<template>
  <RjModal
    width="1000px"
    :title="$t('userManage.oneClickTitle')"
    :visible="value"
    @ok="handleOk"
    :okButtonProps="{
      props: {
        disabled: !Boolean(selectedRowKeys.length),
      },
    }"
    :bodyStyle="{ padding: '20px' }"
    :afterClose="afterClose"
    :okText="$t('userManage.oneClickNext')"
    @cancel="$emit('set', false)"
  >
    <p style="color: #000">
      {{
        $t('userManage.oneClickSureToSendEmail', {
          vpnNum: statusCount.vpnServer,
        })
      }}
    </p>

    <p style="color: #999">
      {{ $t('userManage.oneClickTip') }}
    </p>

    <RjTableEn
      :columns="columns"
      :dataSource="data"
      ref="table"
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      class="mt-20"
      :pagination="pagination"
      :loading="loading"
      rowKey="uuid"
      :scroll="{ y: 250 }"
      @change="handleTableChange"
    >
    </RjTableEn>
    <OneClick2Modal
      @ok="$emit('set', false)"
      :sendAccounts="sendAccounts"
      ref="oneClick2Modal"
      v-model="show"
    />
  </RjModal>
</template>

<script>
import OneClick2Modal from './OneClick2Modal.vue';
import RjTableEn from '@/components/rj-table-en';
import { requestHttp, maccApi } from '@utils/index';
import moment from 'moment-timezone';
import { mapState } from 'vuex';
export default {
  components: {
    RjTableEn,
    OneClick2Modal,
  },
  props: {
    value: Boolean,
  },
  model: {
    prop: 'value',
    event: 'set',
  },
  data() {
    const columns = [
      {
        title: this.$t('userManage.account'),
        dataIndex: 'username',
        key: 'username',
        align: 'center',
      },
      {
        title: this.$t('userManage.password'),
        dataIndex: 'password',
        key: 'password',
        align: 'center',
      },
      {
        title: this.$t('userManage.userGroup'),
        dataIndex: 'userGroupName',
        key: 'userGroupName',
        align: 'center',
      },
      {
        title: this.$t('userManage.createdAt'),
        dataIndex: 'createTime',
        key: 'createTime',
        align: 'center',
      },
      {
        title: this.$t('userManage.VPN'),
        dataIndex: 'vpnEnableStatus',
        key: 'vpnEnableStatus',
        align: 'center',
        width: 100,
      },
      {
        title: this.$t('userManage.accountStatus'),
        dataIndex: 'accountStatusDesc',
        key: 'accountStatusDesc',
        align: 'center',
        filterMultiple: false,
        filters: [
          {
            text: this.$t('common.all'),
            value: '',
          },
          {
            text: this.$t('userManage.unActivated'),
            value: 1,
          },
          {
            text: this.$t('userManage.activated'),
            value: 2,
          },
          {
            text: this.$t('userManage.expired'),
            value: 3,
          },
        ],
      },
      {
        title: this.$t('userManage.sendStatus'),
        dataIndex: 'sendStatusDesc',
        key: 'sendStatusDesc',
        align: 'center',
        filterMultiple: false,
        filters: [
          {
            text: this.$t('common.all'),
            value: '',
          },
          {
            text: this.$t('userManage.oneClickSent'),
            value: 1,
          },
          {
            text: this.$t('userManage.oneClickUnsent'),
            value: 0,
          },
        ],
      },
    ];
    return {
      columns,
      show: false,
      pagination: {
        showQuickJumper: true,
        showSizeChanger: true,
        showLessItems: true,
        pageSizeOptions: ['10', '20', '30', '50', '100', '500'],
        total: 0,
        current: 1,
        pageSize: 10,
      },
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      data: [],
      sendAccounts: [],
      statusCount: {},
    };
  },
  watch: {
    value(val) {
      val && this.queryData();
    },
  },
  computed: {
    ...mapState('User', ['tenantInfo', 'userInfo']),
    ...mapState('Group', ['groupId', 'groupInfo']),
  },
  methods: {
    handleTableChange(pagination, filters) {
      let { current, pageSize } = pagination;
      this.pagination = pagination;
      this.queryData(current, pageSize, filters);
    },
    // 查询数据
    async queryData(current = 1, pageSize = 10, filters = {}) {
      let querys = {
        start: (current - 1) * pageSize,
        pageSize,
        tenantId: this.tenantInfo.tenantId,
        name: '',
        status: filters.accountStatusDesc?.[0] || '',
        isSentMail: filters.sendStatusDesc?.[0] ?? '',
        isBlankMail: 1,
      };
      let replaces = {
        tenantName: encodeURI(this.tenantInfo.tenantName),
        groupId: this.groupId,
      };
      this.loading = true;
      const res = await requestHttp({
        api: `${maccApi.USER_MANAGE_ACCOUNT_GET}`,
        method: 'GET',
        querys,
        replaces,
      });
      this.loading = false;
      if (!res.code) {
        this.pagination.current = current;
        this.statusCount.vpnServer = res.voucherData.vpnNum;
        const accountStatusMap = {
          1: this.$t('userManage.unActivated'),
          2: this.$t('userManage.activated'),
          3: this.$t('userManage.expired'),
        };
        const sendStatusMap = {
          0: this.$t('userManage.oneClickUnsent'),
          1: this.$t('userManage.oneClickSent'),
          2: this.$t('common.all'),
        };
        this.pagination.total = res?.voucherData?.count ?? 0;
        let timeFormatStr = 'YYYY-MM-DD HH:mm:ss';
        let list = (res?.voucherData?.list || []).map((item) => {
          item.accountStatusDesc = accountStatusMap[item.status];
          item.sendStatusDesc = sendStatusMap[item.isSentMail];
          item.createTime = moment(Number(item.createTime))
            .tz(this.groupInfo.timezone)
            .format(timeFormatStr);
          item.vpnEnableStatus = item.vpnEnable
            ? this.$t('userManage.VPNEnable')
            : this.$t('userManage.VPNDisabled');
          return item;
        });
        this.data = list;
      }
    },
    handleOk() {
      this.sendAccounts = this.selectedRows.map((item) => ({
        portalAccount: item.username,
        portalPassword: item.password,
        vpnAccount: item.username,
        vpnPassword: item.password,
        email: item.email || '',
        company: this.userInfo.company,
        uuid: item.uuid,
        tenantId: String(this.tenantInfo.tenantId),
        groupId: String(this.groupId),
        vpnEnable: item.vpnEnable,
      }));
      this.show = true;
    },
    afterClose() {
      this.selectedRowKeys = [];
      this.selectedRows = [];
    },
    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
  },
};
</script>

<style lang="less" scoped>
.box {
  color: #8c8c8c;
  .left {
    color: #000;
  }
  .center {
    color: #018903;
  }
  .right {
    color: #2b6afd;
  }
}
.split {
  background: #e8e8e8;
  width: 1px;
  height: 25px;
}
.mt-20 {
  margin-top: 20px;
}
</style>
